$(function (){
	$.init();
	var param = parseUrlSearch();
	var cache = {};
	var curSku = 0;
	$(document).on('click', '.spec-list .button', onChoose);
	$(document).on('click', '.j-buy', onBuy);
	$(document).on('click', '.minus', onMinus);
	$(document).on('click', '.add', onAdd);
	$(document).on('click', '.join', joinCar);
	renderInfo()

	function fetchInfo(callback) {
		$.ajax({
			url: HOST + '/api/spu/get',
			data: {
				spuCode: param.id
			},
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function renderInfo () {
		fetchInfo(function (data) {
			cache = data;
			var html = getCommonProductItemHtml(data);
			$('.content').html(html);
		});
	}

	function onChoose (e) {
		var $target = $(e.currentTarget);
		$target.siblings().removeClass('button-danger').addClass('button-dark');
		$target.toggleClass('button-dark button-danger');
		curSku = 0;
		var product = {};
		$('.spec-list .button-danger').forEach(function (item) {
			var $item = $(item);
			product[$item.closest('li').data('spec')] = $item.html();
		});

		var reason = [];
		for(var key in cache.skuSpecifications) {
			if(!product[key]) {
				reason.push(cache.specificationName[key]);
			}
		}
		if(reason.length > 0) {
			$('.form_wrap .price').html('价格：--');
			$('.form_wrap .spec').html('请选择 ' + reason.join('、'));
			$('.form_wrap .surplus').html('剩余：--');
			return;
		}else {
			cache.skus.forEach(function (sku) {
				var spec = JSON.parse(sku.specification);
				for(var spec_key in spec) {
					if(spec[spec_key] !== product[spec_key]) {
						return;
					}
				}
				curSku = sku;
			});
			if(curSku) {
				$('.form_wrap .price').html('价格：' + curSku.price);
				$('.form_wrap .spec').html('您已选择 ' + Object.values(product).join(' '));
				$('.form_wrap .surplus').html('剩余：' + curSku.inventoryNum);
			}else{
				$('.form_wrap .price').html('价格：--');
				$('.form_wrap .spec').html('请选择其他');
				$('.form_wrap .surplus').html('剩余：无货');
			}
			
			return;
		}
	}

	function onBuy() {
		var tip = '';
		$('.spec-list li').forEach(function(item) {
			var $item = $(item);
			var spec = $item.data('spec');
			if(!spec) {
				return;
			}
			if($('.button-danger', $item).length == 0) {
				tip += (spec + '、');
			}
		});
		tip && (tip = '请选择' + tip.slice(0, -1));
		if(tip) {
			$.alert(tip);
			return;
		}
		createOrder(function (orderId) {
			pay({
				price: 0.01,
				callback: function() {
					$.alert('支付成功，尽快为您发货！感谢您的支持！');
				},
				errCallback: function () {
					$.ajax({
						url: HOST + '/api/mini-program/pay/fail',
						type: 'post',
						data: JSON.stringify({
							openid: SELFID,
							orderCode: orderId,
							errMsg: 'cancel'
						}),
						success: function(res) {
							callback && callback(res.content);
						}
					});
				}
			});
		});
		
	}

	function createOrder (callback) {
		$.ajax({
			url: HOST + '/api/order/create',
			type: 'post',
			data: JSON.stringify({
				openid: SELFID,
				details: [{
					skuCode: curSku.skuCode,
					qty: +$('.num').html()
				}],
				isShoppingCart: false
			}),
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function onMinus (e) {
		var $num = $('.spec-ipt .num');
		var num = +$num.html();
		num = (num == 0 ? num : num - 1);
		$num.html(num);
		$('.total span').html(+$('.price').data('price') * num);
	}

	function onAdd (e) {
		var $num = $('.spec-ipt .num');
		var num = +$num.html() + 1;
		$num.html(num);
		$('.total span').html(+$('.price').data('price') * num);
	}

	function getCommonProductItemHtml (data) {
		var temp = '';
		curSku = data.skus[0];
		var first_item_spec = JSON.parse(curSku.specification);
		for(var key in data.skuSpecifications) {
			temp += getSpecItemHtml({
				label: data.specificationName[key],
				labelKey: key,
				specs: data.skuSpecifications[key],
				value: first_item_spec[key]
			}, );
		}
		return '<div class="img-wrap">\
					<img src="'+data.spuImage+'">\
				</div>\
				<div class="info_wrap">\
					<div style="padding: 0.2rem 0;">\
						<span class="alias">'+data.spuName+'</span>\
					</div>\
					<div class="des">'+(data.location||data.sexSupport)+'</div>\
				</div>\
				<div class="form_wrap">\
					<div class="spec-ipt">\
						<div class="price" data-price="'+curSku.price+'">价格: '+curSku.price+'</div>\
						<div class="surplus">剩余：'+curSku.inventoryNum+'</div>\
						<div class="spec">您已选择 '+Object.values(first_item_spec).join(' ')+'</div>\
						<ul class="spec-list">'+temp+'\
							<li>\
								<span class="spec-tit">购买数量</span>\
								<span style="float: right;">\
									<span class="iconfont minus">&#xe6fe;</span>\
									<span class="num">1</span>\
									<span class="iconfont add">&#xe6b9;</span>\
								</span>\
							</li>\
						</ul>\
					</div>\
				</div>';
	}

	function getSpecItemHtml (data) {
		return '<li data-spec="'+data.labelKey+'">\
					<div class="spec-tit">'+data.label+'</div>\
					<div>'+data.specs.reduce(function(memo, item){
						return memo + '<a href="#" class="button '+(data.value==item?'button-danger':'button-dark')+'">'+item+'</a>'
					}, '')+'</div>\
				</li>';
	}

	function joinCar() {
		if(!curSku) {
			$.alert('暂无此货，请选择其他商品！');
			return;
		}
		$.ajax({
			url: HOST + '/api/shopcart/sku/batchUpdate',
			type: 'post',
			data: JSON.stringify({
				openid: SELFID,
				skus: [{
					skuCode: curSku.skuCode,
					qty: +$('.num').html()
				}]
				
			}),
			success: function(res) {
				$.alert('加入成功，请移步到购物车中查看。');
			}
		});
	}
});
